import { contextBridge } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  SelectGeojsonFile: (): Promise<string> => electronAPI.ipcRenderer.invoke('window-select-geojson'),
  SelectTifFile: (): Promise<string> => electronAPI.ipcRenderer.invoke('window-select-tif'),
  SelectFolder: (): Promise<string> => electronAPI.ipcRenderer.invoke('window-select-folder'),
  ReadConfigFile: (): Promise<unknown> => electronAPI.ipcRenderer.invoke('read-config-file'),
  WriteConfigFile: (config: unknown): Promise<boolean> =>
    electronAPI.ipcRenderer.invoke('write-config-file', config),

  StartProcess: (arg: string): Promise<boolean> =>
    electronAPI.ipcRenderer.invoke('window-start-process', arg),
  StopProcess: (): Promise<boolean> => electronAPI.ipcRenderer.invoke('window-stop-process'),
  IsProcessRunning: (): Promise<boolean> =>
    electronAPI.ipcRenderer.invoke('window-is-process-running')
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
